/**
 * TODO页面的入口
 */

import xs, { Stream } from 'xstream';
import { VNode } from '@cycle/dom';
import isolate from '@cycle/isolate';
import { TodoListSources, TodoListSinks, TodoListReducer, TodoListAction, TodoListState, TodoState } from '../../types';
import intent from './intent';
import view from './view';
import model from './model';
import List from './List';

/**
 * List 的透镜
 */
export const listLens = {
    /**
     * 获取子控件的state
     */
    get: (state : TodoListState) => {
        return state.list.filter(state.filterFn);
    },
    /**
     * 根据子控件的状态变化返回更新state
     */
    set: (state : TodoListState, nextFilteredList : Array<TodoState>) => {
        const prevFilteredList = state.list.filter(state.filterFn);
        const newList = state.list
            .map(item => nextFilteredList.find(t => t.key === item.key) || item)
            .filter(item =>
            prevFilteredList.some(t => t.key === item.key) &&
            nextFilteredList.some(t => t.key === item.key)
            );
        return {
            ...state,
            list: newList,
        };
    }
}

/**
 * 返回TodoList的组件
 * @param sources 
 */
export default function TodoList(sources : TodoListSources) : TodoListSinks
{

    const state$ = sources.onion.state$;
    const actions = intent(sources.DOM, sources.history);
    const parentReducer$ = model(actions);

    const listSinks = isolate(List, { onion: listLens })(sources);
    const listVDom$ = listSinks.DOM;
    const listReducer$ = listSinks.onion;

    const vdom$ = view(state$, listVDom$);
    const reducer$ = xs.merge(parentReducer$, listReducer$);
    return {
        DOM: vdom$,
        onion: reducer$
    };
}